#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./esb/esb/bkauth/validators.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
from common.base_validators import BaseValidator, ValidationError
from esb.bkcore.models import UserAuthToken
from esb.utils.func_ctrl import FunctionControllerClient

class UserAuthValidator(BaseValidator):
    """
    validate user
    """

    def __init__(self, *args, **kwargs):
        super(UserAuthValidator, self).__init__(*args, **kwargs)

    def validate(self, request):
        kwargs = request.g.kwargs
        auth_token = kwargs.get('auth_token')
        if auth_token:
            token_info = self.validate_auth_token(kwargs.get('app_code'), auth_token)
            self.sync_current_username(request, token_info['username'])
            return
        bk_token = kwargs.get('bk_token')
        if bk_token:
            from components.bk.apis.bk_login.is_login import IsLogin
            check_result = IsLogin().invoke(kwargs={'bk_token': bk_token}, request_id=request.g.request_id)
            if not check_result['result']:
                raise ValidationError(u'用户认证失败，请检查bk_token是否有效')
            self.sync_current_username(request, check_result.get('data', {}).get('username', ''))
            return
        username = kwargs.get('username')
        if username and FunctionControllerClient.is_skip_user_auth(kwargs.get('app_code')):
            self.sync_current_username(request, username)
            return
        raise ValidationError(u'用户认证失败，请提供有效的用户身份信息')

    def sync_current_username(self, request, username):
        request.g.current_user_username = username

    def validate_bk_token(self):
        pass

    def validate_auth_token(self, app_code, auth_token):
        if not app_code:
            raise ValidationError(u'应用ID [app_code] 不能为空')
        if not auth_token:
            raise ValidationError(u'用户TOKEN [auth_token] 不能为空')
        user_auth_token = UserAuthToken.objects.filter(app_code=app_code, auth_token=auth_token).first()
        if not user_auth_token:
            raise ValidationError(u'指定的用户TOKEN [auth_token] 不存在')
        if user_auth_token.has_expired():
            raise ValidationError(u'指定的用户TOKEN [auth_token] 已经过期，请重新申请授权')
        return user_auth_token.get_info()
